const mongoose = require('mongoose');
const db ="mongodb://localhost/douban"
mongoose.Promise = global.Promise;
exports.connect =()=>{
    let maxConnectTimes = 0;
    return new Promise((resolve,reject)=>{
        if(process.env.NODE_ENV!=='production'){
            mongoose.set('debug',true)
        }
        mongoose.connect(db,{useNewUrlParser: true});
        mongoose.connection.on('disconnected',()=>{
            maxConnectTimes++;
            if(maxConnectTimes<5){
                mongoose.connect(db);
            }else{
                throw new Error('数据库挂了吧')
            }
            
        })
        mongoose.connection.on('error',err=>{
            reject(err);
        })
        mongoose.connection.on('open',()=>{
            const Dog = mongoose.model('Dog',{name:String})
            const doga= new Dog({name:"dogo"})
            doga.save().then(()=>{
                console.log('wang')
            })
            console.log('MongdoDB Connect successfully')
        })
    })
   
}